#!/usr/bin/env python3
"""
测试输出路径更新工具

用于将测试脚本中的输出路径统一更新为logs目录
"""

import os
import re
import sys

def update_test_outputs():
    """更新测试脚本的输出路径"""
    test_dir = os.path.dirname(__file__)
    logs_dir = os.path.join(os.path.dirname(test_dir), 'logs')
    
    if not os.path.exists(logs_dir):
        os.makedirs(logs_dir)
    
    # 需要更新的文件模式
    patterns = [
        (r"output_dir\s*=\s*['\"]output['\"]", "logs_dir = os.path.join(os.path.dirname(__file__), '..', 'logs')"),
        (r"os\.path\.join\(output_dir", "os.path.join(logs_dir"),
        (r"os\.makedirs\(output_dir", "os.makedirs(logs_dir"),
    ]
    
    updated_files = []
    
    for filename in os.listdir(test_dir):
        if filename.endswith('.py') and filename.startswith('test_'):
            filepath = os.path.join(test_dir, filename)
            
            with open(filepath, 'r', encoding='utf-8') as f:
                content = f.read()
            
            original_content = content
            
            # 应用模式替换
            for old_pattern, new_pattern in patterns:
                content = re.sub(old_pattern, new_pattern, content)
            
            # 添加导入测试工具（如果需要）
            if 'get_test_output_path' not in content and 'plt.savefig' in content:
                # 在适当位置添加导入
                if 'from test.test_utils import' not in content:
                    # 在文件开头添加导入
                    import_line = "from test.test_utils import get_test_output_path"
                    lines = content.split('\n')
                    insert_pos = 0
                    for i, line in enumerate(lines):
                        if line.strip() and not line.startswith('#') and not line.startswith('"""'):
                            insert_pos = i
                            break
                    lines.insert(insert_pos, import_line)
                    content = '\n'.join(lines)
            
            if content != original_content:
                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(content)
                updated_files.append(filename)
    
    return updated_files

if __name__ == "__main__":
    updated = update_test_outputs()
    if updated:
        print("已更新以下文件的输出路径:")
        for filename in updated:
            print(f"  - {filename}")
    else:
        print("没有发现需要更新的文件")